package com.alex.controller.System;


import com.alex.controller.System.entity.ChatCompletionChunk;
import com.alex.controller.System.entity.Choice;
import com.alex.controller.System.entity.ChatEntity;
import com.alibaba.fastjson2.JSONObject;
import common.util.StringUtil;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Service
public class AliClientToolNoStreamJson {

    public static void main(String[] args) {
        List<ChatEntity> list = new ArrayList<>();
        list.add(new ChatEntity("system","任务描述：根据用户提供的关键词生成20个与之意思相近或相关的扩展词。这些词汇需要是英文检索词，并且每个英文词都需要附带中文翻译。 输出格式要求：请严格按照以下JSON格式返回结果，不要包含任何额外的信息。  [ {\"en\":\"example_word1\",\"cn\":\"示例词1\"}, {\"en\":\"example_word2\",\"cn\":\"示例词2\"}, ... {\"en\":\"example_word20\",\"cn\":\"示例词20\"} ]   具体步骤： 1. 分析用户输入词的含义及其相关领域。 2. 基于分析结果，找出20个与用户输入词意思相近或相关的英文词汇。 3. 对每一个找到的英文词汇提供准确的中文翻译。 4. 按照指定的JSON格式组织答案并返回。 注意事项： - 确保所有生成的词汇都与用户输入词紧密相关。 - 中文翻译应准确反映英文词汇的意思。 - 输出必须严格遵循给定的JSON结构，不添加额外的文字说明或其他内容。"));
        list.add(new ChatEntity("user","ecdna"));
        String send = send(list);
        System.out.println(send);
    }

    public static String send(List<ChatEntity> msgEntities) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        Request request = sendForJson(msgEntities);

        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {

            e.printStackTrace(System.err);
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (null != response) {
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                InputStream inputStream = responseBody.byteStream();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {

                        if ("[DONE]".equals(line) || "data: [DONE]".equals(line)) {
                            break;
                        }
                        line = line.replaceAll("data: ", "").trim();
                        try {
                            if (StringUtil.isNotNull(line)) {
                                ChatCompletionChunk chatCompletionChunk = JSONObject.parseObject(line, ChatCompletionChunk.class);
                                List<Choice> choices = chatCompletionChunk.getChoices();
                                for (Choice choice : choices) {
                                    String content = choice.getDelta().getContent().replaceAll("\n\n", "\n");
                                    char[] charArray = content.toCharArray();
                                    stringBuilder.append(content);
                                }
                            }

                        } catch (Exception e) {

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
        return stringBuilder.toString();
    }

    public static Request sendForJson(List<ChatEntity> msgEntities) {
        String string = "{\n" +
                "    \"messages\": " + JSONObject.toJSONString(msgEntities) +
                "      ,\n" +
                "    \"model\": \"qwen-plus\",\n" +
                "    \"response_format\": {\n" +
                "        \"type\": \"json_object\"\n" +
                "    },\n" +
                "    \"frequency_penalty\": 0,\n" +
                "    \"max_tokens\": 2000,\n" +
                "    \"presence_penalty\": 0,\n" +
                "    \"stop\": null,\n" +
                "    \"enable_search \": true,\n" +
                "    \"stream\": true,\n" +
                "    \"temperature\": 1,\n" +
                "    \"enable_search\": true,\n" +
                "    \"top_p\": 0.9\n" +
                "}";
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, string);
        return new Request.Builder().url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-78636476472d45a1835795ca82c3d7d6")
                .build();
    }

    public  void  sendToClint(HttpServletResponse response,String msg){
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


}
